/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.linde.service;

import java.util.Optional;

import org.doll.it.base.enums.StatusEnum;
import org.doll.it.base.util.AssertUtils;
import org.doll.it.base.util.StringUtils;
import org.doll.it.linde.dao.StateDAO;
import org.doll.it.linde.domain.StateDO;
import org.doll.it.nora.annotation.BackupSupport;
import org.doll.it.sequence.enums.BusinessTypeEnum;
import org.doll.it.sequence.service.DollSequenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StateService {

	@Autowired
	private DollSequenceService sequenceService;

	@Autowired
	private StateDAO stateDAO;

	/**
	 * 新增状态
	 * @param name 名称，必须唯一
	 * @param displayName 显示名称
	 * @param desc 描述
	 * @return 返回值
	 */
	public long insert(String name, String displayName, String desc) {
		AssertUtils.hasText(name, "'name' must not be empty.");
		AssertUtils.hasText(displayName, "'displayName' must not be empty.");

		long id = sequenceService.nextId(BusinessTypeEnum.LINDE_STATE);

		StateDO stateDO = StateDO.builder().name(name).displayName(displayName).description(desc).build();
		stateDO.setId(id);
		stateDAO.insert(stateDO);

		return id;
	}

	/**
	 * 修改普通属性
	 * @param id
	 * @param name
	 * @param displayName
	 * @param discription
	 */
	public void update(long id, String name, String displayName, String discription) {
		AssertUtils.verifyId(id);

		boolean hasChange = StringUtils.hasText(name) || StringUtils.hasText(displayName)
				|| StringUtils.hasText(discription);
		if (hasChange) {
			Optional<StateDO> optional = stateDAO.findById(id);
			AssertUtils.exist(optional, id);

			optional.ifPresent((x) -> {
				if (StringUtils.hasText(name)) {
					x.setName(name.trim());
				}
				if (StringUtils.hasText(displayName)) {
					x.setDisplayName(displayName.trim());
				}
				if (StringUtils.hasText(discription)) {
					x.setDescription(discription.trim());
				}
				stateDAO.save(x);
			});
		}
	}

	/**
	 * 更新State的状态(隐藏/显示)
	 * @param id 
	 * @param hidden true:隐藏; flase:显示
	 */
	public void updateStatus(long id, boolean hidden) {
		AssertUtils.verifyId(id);

		Optional<StateDO> optional = stateDAO.findById(id);
		AssertUtils.exist(optional, id);

		optional.ifPresent((x) -> {
			StatusEnum resultEnum = hidden ? StatusEnum.HIDDEN : StatusEnum.NORMAL;
			if (x.getStatus() != resultEnum) {
				x.setStatus(resultEnum);
				stateDAO.save(x);
			}
		});

	}

	/**
	 * 删除对象（如果有使用，则不能删除）
	 * @param id
	 * @return 
	 */
	@BackupSupport("delete state")
	public StateDO delete(long id) {
		AssertUtils.verifyId(id);

		Optional<StateDO> optional = stateDAO.findById(id);
		AssertUtils.exist(optional, id);

		optional.ifPresent((x) -> {
			AssertUtils.deleteUsingObject(x.getUsingTypeIds(), id);
			stateDAO.delete(x);
		});

		return optional.get();
	}

}
